package ThreadDemo;

/*
 * Author: JacksonCoder
 * FileName: PingPongSemaphore
 * Version: 1.0.0
 * Date: 2025/5/14
 */

import java.util.concurrent.Semaphore;

public class PingPongSemaphore {
    private final Semaphore pingSem = new Semaphore(1);
    private final Semaphore pongSem = new Semaphore(0);

    public void ping() throws InterruptedException{
        pingSem.acquire();
        System.out.println("ping");
        pongSem.release();
    }

    public void pong() throws  InterruptedException{
        pongSem.acquire();
        System.out.println("pong");
        pingSem.release();
    }

    public static void main(String[] args) throws InterruptedException {
        PingPongSemaphore pp = new PingPongSemaphore();

        Thread t1 = new Thread(() -> {
            try {
                for (int i = 0; i < 10; i++) {
                    pp.ping();
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });

        Thread t2 = new Thread(() -> {
            try {
                for (int i = 0; i < 10; i++) {
                    pp.pong();
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });

        t1.start();
        t2.start();

        // Wait for both threads to complete

        t1.join();
        t2.join();
    }
}
